package com.example.blog.interceptor;

import com.example.blog.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class AdminInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("Authorization");

        //解析 token 并获取 role 信息
        Map<String, Object> map = JwtUtil.parseToken(token);
        Integer role = (Integer) map.get("role");
        if(role == 1){
            return true;// 允许通过
        }
        else{
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);// 403 禁止访问
            return false;// 拦截请求
        }

    }

}
